<?php

namespace App\Services\Upload\Aliyun;


use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use App\Exception\MessageException;
use App\Utils\LoggerUtil;
use OSS\OssClient;
use function Hyperf\Config\config;

class AliyunOss
{

    private static $config;
    private static $bucket;
    private static $endpoint;
    private static $roleArn;
    private static $serveEndpoint;

    public function __construct()
    {
        self::$config['accessKeyId'] = config('oss.aliyun.access_key_id');
        self::$config['accessKeySecret'] = config('oss.aliyun.access_key_secret');
        self::$bucket = config('oss.aliyun.bucket');
        self::$endpoint = config('oss.aliyun.endpoint');
        self::$roleArn = config('oss.aliyun.role_arn');
        self::$serveEndpoint = config('oss.aliyun.serve_endpoint');
    }

    /**
     * 文件上传至阿里云oss（简单上传） 返回url
     * @param $localFilePath // 被上传的图片地址
     * @param $uploadFilePath // 上传到OSS的路径
     * @return mixed
     * @throws \OSS\Http\RequestCore_Exception
     */
    public function simpleUpload($localFilePath, $uploadFilePath)
    {
        try {
            $ossClient = new OssClient(self::$config['accessKeyId'], self::$config['accessKeySecret'], self::$endpoint);
            $result = $ossClient->uploadFile(self::$bucket, $uploadFilePath, $localFilePath);
            return $result['info']['url'];
        } catch (\Throwable $e) {
            LoggerUtil::write('simpleUpload_to_aliyun_oss_error', $e->getMessage());
            throw new MessageException('上传失败');
        }
    }

    /**
     * 文件上传至阿里云oss（简单上传） 返回url
     * @param $content // object，被上传的文件对象
     * @param $uploadFilePath // 上传到OSS的路径
     * @return mixed
     * @throws \OSS\Http\RequestCore_Exception
     */
    public function uploadFile($content, $uploadFilePath)
    {
        try {
            $ossClient = new OssClient(self::$config['accessKeyId'], self::$config['accessKeySecret'], self::$endpoint);
            $result = $ossClient->putObject(self::$bucket, $uploadFilePath, $content);
            return $result['info']['url'];
        } catch (\Throwable $e) {
            LoggerUtil::write('uploadFile_to_aliyun_oss_error', $e->getMessage());
            throw new MessageException('上传失败');
        }
    }


    /**
     * 获取阿里云oss临时凭证
     * @return array
     */
    public function assumeRole()
    {
        try {
            $config = new \Darabonba\OpenApi\Models\Config(self::$config);
            // $config->endpoint = "sts.cn-hongkong.aliyuncs.com";
            $config->endpoint = self::$serveEndpoint;
            $client = new Sts($config);

            $assumeRoleRequest = new AssumeRoleRequest([
                "roleArn" => self::$roleArn,
                "roleSessionName" => "oss"
            ]);

            $uploadInfo = $client->assumeRole($assumeRoleRequest)->body->toMap();
            $arr["StatusCode"] = 200;
            $arr["AccessKeyId"] = $uploadInfo["Credentials"]["AccessKeyId"];
            $arr["AccessKeySecret"] = $uploadInfo["Credentials"]["AccessKeySecret"];
            $arr["Expiration"] = $uploadInfo["Credentials"]["Expiration"];
            $arr["SecurityToken"] = $uploadInfo["Credentials"]["SecurityToken"];
            return $arr;
        } catch (\Throwable $e) {
            LoggerUtil::write('assumeRole_to_aliyun_oss_error', $e->getMessage());
            throw new MessageException('获取失败');
        }
    }

}